'''
Created on Sep 6, 2011

@author: david
'''
from app.G6.actions import G6Action

class Fetch(G6Action):
    """
    Gather top set of articles for
    viewing.
    """
    def execute(self):
        import logging
        from app.G6.agents import BlogAgent
        import simplejson as json
        articles = None
        
        req = self.request
        
        try:
            # validate session
            if not self.auth_check():
                return self.JSONOutput(json.dumps({"results":"401::Invalid Session"}))
            
            # establish range
            start = int(req.getParameter("start","0"))
            count = int(req.getParameter("count","5"))
            
            # gather data elements
            name = req.getParameter("name",'')

            acct = req.session.getAttribute("acct")
            if name=='undefined':
                name = None
                
            logging.info("++ Getting Blog %s for %s" % (name, acct))
            
            # find the agent
            agent = BlogAgent()
            
            blog = None
            if req.session.has_key("currblog"):
                blog = req.session.getAttribute("currblog")
                if name != blog.name:
                    blog = None
                
            if not name:
                if req.session.has_key("defBlog"):
                    name = req.session.getAttribute("defBlog") 
                else:
                    name = "Default"
            
            if blog and blog.name != name:
                # not it
                blog = None
                
            # get correct blog
            if not blog:
                # get it
                blog = agent.get(acct, name) 
                req.session.setAttribute("currblog", blog)
                if name == "Default":
                    req.session.setAttribute("defBlog",blog.name)

                logging.debug("~~ Got Blog: %s " % blog.name )
            
            # get the current blog and fetch articles
            articles = agent.fetchArticles(blog, start, count)
        
            logging.debug("~~ articles: %s" % articles)
            
            # save as current blog    
            req.session.setAttribute("currblog",blog)
        
        except Exception, ex:
            logging.exception("!! Blog List Exception")
            
            return self.JSONOutput(json.dumps({"results":"500::%s" % str(ex)}))    
        
        json = json.dumps({"results":"200::OK","articles":[a.toJSON() for a in articles], "blog": blog.toJSON() })
        logging.debug("~~ JSON: %s" % json)
    
        return self.JSONOutput(json)
